package com.example.demo.service;

import com.example.demo.mapper.OrderMapper;
import com.example.demo.pojo.Order;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class OrderService {

    @Resource
    private JdbcTemplate jdbcTemplate;
    @Resource
    private OrderMapper orderMapper;

    @Transactional(rollbackFor = Throwable.class)
    @ShardingTransactionType(TransactionType.XA)  // 支持TransactionType.LOCAL, TransactionType.XA, TransactionType.BASE
    public void insert() throws Exception{
//        for (int i = 0; i < 50; i++) {
//            int finalI = i;
//            jdbcTemplate.execute("INSERT INTO sys_order (user_id, status,order_no) VALUES (?, ?,?)", (PreparedStatementCallback<Object>) preparedStatement -> {
//                preparedStatement.setObject(1, finalI);
//                preparedStatement.setObject(2, "1");
//                preparedStatement.setObject(3, "456465465465");
//                preparedStatement.executeUpdate();
//                if(finalI==25){
//                    throw new RuntimeException("caiiuowquroqwr");
//                }
//                return true;
//            });
//        }
        for (int i = 0; i < 10; i++) {
            if(i==9){
                    throw new RuntimeException("caiiuowquroqwr");
                }
            Order order =  new Order();
            order.setUserId(33333L);
            order.setOrderNo("3333333333333");
            order.setStatus("3");
            orderMapper.insertSysOrder(order);
        }

    }
}
